package com.tnovoselec.server.gdjejefrka.beans;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.interactive1.dbutils.ConnectionPool;


/**
 * @author eddie
 */
public abstract class DBBean {

	// private static Log log = LogFactory.getLog("DBBean");
	//private static Log log = new Log("DBBean");

	public long insert() throws SQLException {
		long oid = -1;
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = ConnectionPool.getConnection("gdjejefrka");
			ps = getInsert(con);
			ps.execute();
			ResultSet rs1 = ps.getGeneratedKeys();
			if (rs1 != null) {
				rs1.next();
				oid = rs1.getLong(1);
			}

		} catch (SQLException e) {
			e.printStackTrace();
			throw new SQLException();
		} finally {
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
				}
			}
			ConnectionPool.release("gdjejefrka", con);
		}
		return oid;
	}

	public long insertWithoutAutoIncrement() throws SQLException {
		long oid = -1;
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = ConnectionPool.getConnection("gdjejefrka");
			ps = getInsert(con);
			ps.execute();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new SQLException();
		} finally {
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
				}
			}
			ConnectionPool.release("gluume", con);
		}
		return oid;
	}

	protected abstract PreparedStatement getInsert(Connection con) throws SQLException;

	public void update() throws SQLException {
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = ConnectionPool.getConnection("gdjejefrka");
			ps = getUpdate(con);
			ps.execute();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new SQLException();
		} finally {
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
				}
			}
			ConnectionPool.release("gdjejefrka", con);
		}
	}

	protected abstract PreparedStatement getUpdate(Connection con) throws SQLException;

	public void delete() throws SQLException {
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = ConnectionPool.getConnection("gdjejefrka");
			ps = getDelete(con);
			ps.execute();
		} catch (Exception e) {
			e.printStackTrace();
			throw new SQLException();
		} finally {
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			ConnectionPool.release("gdjejefrka", con);
		}
	}

	protected abstract PreparedStatement getDelete(Connection con) throws SQLException;

}
